package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //处理超过15分钟还未支付的订单
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeOutNoPay(){
        //定义时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //不想这些事情，光想我自己最应该关注的事情
        //查询出来 超时的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        //对超时的订单进行处理
        if (ordersList!=null && ordersList.size()>0){
            ordersList.forEach((Orders orders)->{
                    orders.setStatus(Orders.CANCELLED);
                    orders.setCancelTime(LocalDateTime.now());
                    orders.setCancelReason("订单超时未支付，系统自动取消");
                    orderMapper.update(orders);
                }
            );
        }

    }

    //每天凌晨1点处理前一天还在派送中的订单
    @Scheduled(cron = "0 0 1 1/1 * ?")
    public void processDeliveringOrders(){
        //定义时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        //获得 满足 条件的 orders
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        //判断 并对 满足条件的订单 进行处理
        if(ordersList!=null && ordersList.size()>0){
            ordersList.forEach((Orders orders)->{
                    orders.setStatus(Orders.COMPLETED);
                    orderMapper.update(orders);
                }
            );
        }
    }


}
